package com.qeeyou.apps.android.craftsman.adapter;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.qeeyou.apps.android.craftsman.R;
import com.qeeyou.apps.android.craftsman.activity.order.CancelOrderActivity;
import com.qeeyou.apps.android.craftsman.activity.order.OrderDetailActivity;
import com.qeeyou.apps.android.craftsman.activity.order.ServiceEvaluateActivity;
import com.qeeyou.apps.android.craftsman.common.Contants;
import com.qeeyou.apps.android.craftsman.fragment.MeFragment;
import com.qeeyou.apps.android.craftsman.po.OrderInfo;
import com.qeeyou.apps.android.craftsman.utils.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by xuchengxiong on 2017/12/17.
 */

public class OrderAdapter extends BaseAdapter {

    private Activity mActivity;
    private List<OrderInfo> orderList;
    private String mStatus;
    private LayoutInflater mLayoutInflater;

    public OrderAdapter(Activity activity, List<OrderInfo> orderList, String status) {
        mActivity = activity;
        mStatus = status;
        mLayoutInflater = LayoutInflater.from(mActivity);
        if (this.orderList == null) {
            this.orderList = new ArrayList<OrderInfo>();
        }
        this.orderList.clear();
        if (orderList != null && orderList.size() > 0) {
            this.orderList.addAll(orderList);
        }
    }

    public void setItems(List<OrderInfo> orderList, String status) {
        mStatus = status;
        if (this.orderList == null) {
            this.orderList = new ArrayList<OrderInfo>();
        }
        this.orderList.clear();
        if (orderList != null && orderList.size() > 0) {
            this.orderList.addAll(orderList);
        }
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        int count = this.orderList != null ? this.orderList.size() : 0;
        return count;
    }

    @Override
    public OrderInfo getItem(int i) {
        if (i < 0 || i >= this.orderList.size()) {
            return null;
        }
        return this.orderList.get(i);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (mStatus.equalsIgnoreCase(Contants.ORDER_STATUS_TODO)) {
            View view = convertView;
            ToReceiveViewHolder holder = null;
            if (view != null && (view.getTag() instanceof ToReceiveViewHolder)) {
                holder = (ToReceiveViewHolder) view.getTag();
            } else {
                view = mLayoutInflater.inflate(R.layout.view_item_order_to_receive, null, false);
                holder = new ToReceiveViewHolder();
                holder.txtvName = (TextView) view.findViewById(R.id.txtvName4ItemOrderToReceive);
                holder.txtvPrice = (TextView) view.findViewById(R.id.txtvPrice4ItemOrderToReceive);
                holder.txtvNo = (TextView) view.findViewById(R.id.txtvNo4ItemOrderToReceive);
                holder.txtvTime = (TextView) view.findViewById(R.id.txtvTime4ItemOrderToReceive);
                holder.btnCancel = (Button) view.findViewById(R.id.btnCancel4ItemOrderToReceive);
                holder.btnLook = (Button) view.findViewById(R.id.btnLook4ItemOrderToReceive);
                view.setTag(holder);
            }
            final OrderInfo orderInfo = this.orderList.get(position);
            if (orderInfo != null) {
                holder.txtvName.setText(orderInfo.getShopname());
                if(orderInfo.getOrderprice() == null || orderInfo.getOrderprice().trim().equalsIgnoreCase("")) {
                    holder.txtvPrice.setVisibility(View.INVISIBLE);
                } else {
                    holder.txtvPrice.setVisibility(View.VISIBLE);
                    holder.txtvPrice.setText("￥" + orderInfo.getOrderprice() + "元");
                }
                holder.txtvNo.setText("工单编号:" + orderInfo.getOrderno());
                holder.txtvTime.setText("预约服务时间: " + orderInfo.getServicetime());
            }
            holder.btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //取消订单
                    String orderId = orderInfo.getOrderid();
                    Intent intent = new Intent(mActivity, CancelOrderActivity.class);
                    intent.putExtra("orderId", orderId);
                    mActivity.startActivity(intent);
                }
            });
            holder.btnLook.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //订单详情
                    Intent intent = new Intent(mActivity, OrderDetailActivity.class);
                    intent.putExtra("orderInfo", orderInfo);
                    mActivity.startActivity(intent);
                }
            });
            return view;
        } else if (mStatus.equalsIgnoreCase(Contants.ORDER_STATUS_DOING)) {
            View view = convertView;
            ToInstallViewHolder holder = null;
            if (view != null && (view.getTag() instanceof ToInstallViewHolder)) {
                holder = (ToInstallViewHolder) view.getTag();
            } else {
                view = mLayoutInflater.inflate(R.layout.view_item_order_to_install, null, false);
                holder = new ToInstallViewHolder();
                holder.txtvName = (TextView) view.findViewById(R.id.txtvName4ItemOrderToInstall);
                holder.txtvPrice = (TextView) view.findViewById(R.id.txtvPrice4ItemOrderToInstall);
                holder.imgvAvatar = (ImageView) view.findViewById(R.id.imgvAvatar4ItemOrderToInstall);
                holder.txtvCraftsman = (TextView) view.findViewById(R.id.txtvCraftsman4ItemOrderToInstall);
                holder.imgvGender = (ImageView) view.findViewById(R.id.imgvGender4ItemOrderToInstall);
                holder.txtvMobile = (TextView) view.findViewById(R.id.txtvMobile4ItemOrderToInstall);
                holder.txtvNo = (TextView) view.findViewById(R.id.txtvNo4ItemOrderToInstall);
                holder.txtvTime = (TextView) view.findViewById(R.id.txtvTime4ItemOrderToInstall);
                holder.btnContact = (Button) view.findViewById(R.id.btnContact4ItemOrderToInstall);
                holder.btnLook = (Button) view.findViewById(R.id.btnLook4ItemOrderToInstall);
                view.setTag(holder);
            }
            final OrderInfo orderInfo = this.orderList.get(position);
            if (orderInfo != null) {
                holder.txtvName.setText(orderInfo.getShopname());
                if(orderInfo.getOrderprice() == null || orderInfo.getOrderprice().trim().equalsIgnoreCase("")) {
                    holder.txtvPrice.setVisibility(View.INVISIBLE);
                } else {
                    holder.txtvPrice.setVisibility(View.VISIBLE);
                    holder.txtvPrice.setText("￥" + orderInfo.getOrderprice() + "元");
                }
                holder.txtvCraftsman.setText(orderInfo.getMastername());
                holder.txtvMobile.setText(orderInfo.getContactphone());
                holder.txtvNo.setText("工单编号:" + orderInfo.getOrderno());
                holder.txtvTime.setText("上门安装时间: " + orderInfo.getServicetime());
                if (orderInfo.getMasteravatar() != null) {
                    String imageUrl = ImageLoader.getInstance().getImageUrl(orderInfo.getMasteravatar());
                    ImageLoader.getInstance().displayHeaderPic(mActivity, imageUrl, holder.imgvAvatar);
                } else {
                    ImageLoader.getInstance().displayImageById(mActivity, R.drawable.ic_message_avatar, holder.imgvAvatar);
                }
                if (orderInfo.getMastersex() == null || !orderInfo.getMastersex().trim().equalsIgnoreCase("1")) {
                    holder.imgvGender.setImageResource(R.drawable.ic_order_gender_female);
                } else {
                    holder.imgvGender.setImageResource(R.drawable.ic_order_gender_male);
                }
            }
            holder.btnContact.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //拨打电话，联系他
                    String telephone = orderInfo.getContactphone();
                    if (telephone == null || telephone.trim().equalsIgnoreCase("")) {
                        Toast.makeText(mActivity, "师傅的联系电话为空!", Toast.LENGTH_LONG).show();
                    } else {
                        callMasterPhone(telephone);
                    }
                }
            });
            holder.btnLook.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, OrderDetailActivity.class);
                    intent.putExtra("orderInfo", orderInfo);
                    mActivity.startActivity(intent);
                }
            });
            return view;
        } else {
            View view = convertView;
            FinishedViewHolder holder = null;
            if (view != null && (view.getTag() instanceof FinishedViewHolder)) {
                holder = (FinishedViewHolder) view.getTag();
            } else {
                view = mLayoutInflater.inflate(R.layout.view_item_order_finished, null, false);
                holder = new FinishedViewHolder();
                holder.txtvName = (TextView) view.findViewById(R.id.txtvName4ItemOrderFinished);
                holder.txtvPrice = (TextView) view.findViewById(R.id.txtvPrice4ItemOrderFinished);
                holder.imgvAvatar = (ImageView) view.findViewById(R.id.imgvAvatar4ItemOrderFinished);
                holder.txtvCraftsman = (TextView) view.findViewById(R.id.txtvCraftsman4ItemOrderFinished);
                holder.imgvGender = (ImageView) view.findViewById(R.id.imgvGender4ItemOrderFinished);
                holder.txtvNo = (TextView) view.findViewById(R.id.txtvNo4ItemOrderFinished);
                holder.txtvTime = (TextView) view.findViewById(R.id.txtvTime4ItemOrderFinished);
                holder.btnEvaluate = (Button) view.findViewById(R.id.btnComment4ItemOrderFinished);
                holder.btnLook = (Button) view.findViewById(R.id.btnLook4ItemOrderFinished);
                view.setTag(holder);
            }
            final OrderInfo orderInfo = this.orderList.get(position);
            if (orderInfo != null) {
                holder.txtvName.setText(orderInfo.getShopname());
                if(orderInfo.getOrderprice() == null || orderInfo.getOrderprice().trim().equalsIgnoreCase("")) {
                    holder.txtvPrice.setVisibility(View.INVISIBLE);
                } else {
                    holder.txtvPrice.setVisibility(View.VISIBLE);
                    holder.txtvPrice.setText("￥" + orderInfo.getOrderprice() + "元");
                }
                holder.txtvCraftsman.setText(orderInfo.getMastername());
                holder.txtvNo.setText("工单编号:" + orderInfo.getOrderno());
                holder.txtvTime.setText("完成安装时间: " + orderInfo.getServicetime());
                if (orderInfo.getMasteravatar() != null) {
                    String imageUrl = ImageLoader.getInstance().getImageUrl(orderInfo.getMasteravatar());
                    ImageLoader.getInstance().displayHeaderPic(mActivity, imageUrl, holder.imgvAvatar);
                } else {
                    ImageLoader.getInstance().displayImageById(mActivity, R.drawable.ic_message_avatar, holder.imgvAvatar);
                }
                if (orderInfo.getMastersex() == null || !orderInfo.getMastersex().trim().equalsIgnoreCase("1")) {
                    holder.imgvGender.setImageResource(R.drawable.ic_order_gender_female);
                } else {
                    holder.imgvGender.setImageResource(R.drawable.ic_order_gender_male);
                }
                if(orderInfo.getOrderstatus().equalsIgnoreCase(Contants.ORDER_STATUS_CANCEL)) {
                    holder.txtvName.setText(orderInfo.getShopname() + " (已取消)");
                    holder.btnEvaluate.setTextColor(mActivity.getResources().getColor(R.color.colorWhite));
                    holder.btnEvaluate.setBackgroundResource(R.drawable.bg_button_solid_gray);
                } else {
                    holder.txtvName.setText(orderInfo.getShopname());
                    if (orderInfo.getCommentstatus() != null && orderInfo.getCommentstatus().trim().equalsIgnoreCase("1")) {
                        //已经评论
                        holder.btnEvaluate.setTextColor(mActivity.getResources().getColor(R.color.colorWhite));
                        holder.btnEvaluate.setBackgroundResource(R.drawable.bg_button_solid_gray);
                    } else {
                        //待评论
                        holder.btnEvaluate.setTextColor(mActivity.getResources().getColor(R.color.colorBlue));
                        holder.btnEvaluate.setBackgroundResource(R.drawable.bg_button_hollow_blue);
                    }
                }

            }
            holder.btnEvaluate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(orderInfo.getOrderstatus().equalsIgnoreCase(Contants.ORDER_STATUS_CANCEL)) {
                        Toast.makeText(mActivity, "已取消订单无法查看评论!", Toast.LENGTH_SHORT).show();
                    } else {
                        if (orderInfo.getCommentstatus() != null && orderInfo.getCommentstatus().trim().equalsIgnoreCase("1")) {
                            //已经评论
                            Toast.makeText(mActivity, "已经评论过该订单了!", Toast.LENGTH_SHORT).show();
                        } else {
                            //待评论
                            Intent intent = new Intent(mActivity, ServiceEvaluateActivity.class);
                            intent.putExtra("orderInfo", orderInfo);
                            mActivity.startActivityForResult(intent, Contants.RequestCode.REQUEST_COMMENT_ORDER);
                        }
                    }
                }
            });
            holder.btnLook.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, OrderDetailActivity.class);
                    intent.putExtra("orderInfo", orderInfo);
                    mActivity.startActivity(intent);
                }
            });

            return view;
        }
    }

    static class ToReceiveViewHolder {
        TextView txtvName;
        TextView txtvPrice;
        TextView txtvNo;
        TextView txtvTime;
        Button btnCancel;
        Button btnLook;
    }

    static class ToInstallViewHolder {
        TextView txtvName;
        TextView txtvPrice;
        ImageView imgvAvatar;
        TextView txtvCraftsman;
        ImageView imgvGender;
        TextView txtvMobile;
        TextView txtvNo;
        TextView txtvTime;
        Button btnContact;
        Button btnLook;
    }

    static class FinishedViewHolder {
        TextView txtvName;
        TextView txtvPrice;
        ImageView imgvAvatar;
        TextView txtvCraftsman;
        ImageView imgvGender;
        TextView txtvNo;
        TextView txtvTime;
        Button btnEvaluate;
        Button btnLook;
    }

    //拨打师傅电话
    private void callMasterPhone(String phoneNumber) {
        if (ContextCompat.checkSelfPermission(mActivity,
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            //没有获得授权，申请授权
            if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity,
                    Manifest.permission.CALL_PHONE)) {
                Toast.makeText(mActivity, "请授权！", Toast.LENGTH_LONG).show();
                // 帮跳转到该应用的设置界面，让用户手动授权
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", mActivity.getPackageName(), null);
                intent.setData(uri);
                mActivity.startActivity(intent);
            } else {
                // 不需要解释为何需要该权限，直接请求授权
                ActivityCompat.requestPermissions(mActivity,
                        new String[]{Manifest.permission.CALL_PHONE}, 500);
            }
        } else {
            // 已经获得授权，可以打电话
            String telephone = phoneNumber;
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + telephone);
            intent.setData(data);
            mActivity.startActivity(intent);
        }
    }

}
